package com.followme.module.common;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Kamil.O
 * Description: Managed by broadcast receivers
 * Date: 04.12.13
 * Time: 23:26
 */
public class ReceiverManager {
    private static List<BroadcastReceiver> receivers = new ArrayList<BroadcastReceiver>();
    private static ReceiverManager ref;
    private Context context;

    private ReceiverManager(Context context){
        this.context = context;
    }

    public static synchronized ReceiverManager init(Context contextApp) {
        if (ref == null) ref = new ReceiverManager(contextApp);
        return ref;
    }

    public static void registerBroadcatReceiver(Context context, String key,
                                                BroadcastReceiver broadcastReceiver){
        Log.d(CommonModuleUtil.TAG_LOG_CAT, "registerBroadcatReceiver: "+key);
        receivers.add(broadcastReceiver);
        IntentFilter filter = new IntentFilter();
        filter.addAction(key);
        context.registerReceiver(broadcastReceiver, filter);
    }

    public static boolean isReceiverRegistered(BroadcastReceiver receiver){
        boolean registered = receivers.contains(receiver);
        Log.i(CommonModuleUtil.TAG_LOG_CAT, "is receiver "+receiver+" " +
                "registered? "+registered);
        return registered;
    }

    public void unregisterReceiver(BroadcastReceiver receiver){
        if (isReceiverRegistered(receiver)){
            receivers.remove(receiver);
            context.unregisterReceiver(receiver);
            Log.i(CommonModuleUtil.TAG_LOG_CAT, "unregistered receiver: "+receiver);
        }
    }

    public static void unregisterReceiver(Context context, BroadcastReceiver receiver){
        if (isReceiverRegistered(receiver)){
            receivers.remove(receiver);
            context.unregisterReceiver(receiver);
            Log.i(CommonModuleUtil.TAG_LOG_CAT, "unregistered receiver: "+receiver);
        }
    }

}
